<template>
  <div class="app-container">
    <div class="filter">
      <el-input v-model="filter.title" clearable placeholder="角色标题" class="filter-input" style="width:200px" @change="getList" />
      <el-input v-model="filter.name" clearable placeholder="角色名称" class="filter-input" style="width:200px" @change="getList" />
      <el-button icon="el-icon-search" type="primary" @click="getList">查询</el-button>
      <el-button icon="el-icon-plus" type="primary" @click="handleCreate">添加</el-button>
    </div>
    <el-table
      ref="adminTable"
      v-loading="loading"
      :data="list"
      row-key="id"
      stripe
      border
      highlight-current-row
      style="width: 100%"
      max-height="750"
    >
      <el-table-column label="ID" prop="id" align="center" width="80">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="角色标题" prop="title" align="center">
        <template slot-scope="{row}">
          <span>{{ row.title }}</span>
        </template>
      </el-table-column>
      <el-table-column label="角色名称" prop="name" align="center">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" prop="action" align="center" fixed="right" width="150">
        <template slot-scope="{row}">
          <el-button type="text" icon="el-icon-edit" @click="handleEdit(row)">修改</el-button>
          <el-button type="text" style="color: red" icon="el-icon-delete" @click="del(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog :visible.sync="dialog" :title="dialogType==='edit'?'修改':'新增角色'" width="700px">
      <el-form ref="roleForm" v-model="temp" :rules="rules" label-position="right" label-width="150px">
        <el-form-item label="角色标题" prop="title">
          <el-input v-model="temp.title" style="width:400px" />
        </el-form-item>
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="temp.name" style="width:400px" />
        </el-form-item>
        <el-form-item label="权限名称">
          <el-tree
            ref="tree"
            :check-strictly="checkStrictly"
            :data="permissionList"
            :props="defaultProps"
            show-checkbox
            node-key="id"
            class="permission-tree"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog=false">取消</el-button>
        <el-button type="primary" @click="save">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { roleList, store, update, destroy } from '@/api/permission/role'
import { permissionList } from '@/api/permission/permission'

export default {
  name: 'PermissionRole',
  data() {
    return {
      filter: {},
      list: [],
      loading: true,
      dialog: false,
      dialogType: 'create',
      rules: {},
      temp: {},
      permissionList: [],
      permissions: [],
      defaultProps: {
        label: 'title',
        children: 'children'
      },
      checkStrictly: true
    }
  },
  mounted() {
    this.getList()
    this.getPermission()
  },
  methods: {
    // 获取管理员列表
    getList() {
      this.loading = true
      roleList(this.filter).then(res => {
        this.list = res.data
        setTimeout(() => {
          this.loading = false
        }, 500)
      })
    },
    getPermission() {
      permissionList().then(res => {
        this.permissionList = res.data
      })
    },
    // 打开新增管理员窗口
    handleCreate() {
      this.temp = {}
      // 清空之前选择的树形组件
      this.permissions = []
      this.dialogType = 'create'
      this.dialog = true
      this.$nextTick(() => {
        this.$refs.tree.setCheckedKeys(this.permissions)
        this.$refs['roleForm'].clearValidate()
      })
    },
    // 打开修改管理员窗口
    handleEdit(row) {
      this.permissions = []
      this.temp = Object.assign({}, row)
      this.temp.permissions.forEach(permission => {
        this.permissions.push(permission.id)
      })
      this.dialogType = 'edit'
      this.dialog = true
      this.$nextTick(() => {
        this.$refs['roleForm'].clearValidate()
        this.$refs.tree.setCheckedKeys(this.permissions)
      })
    },
    // 提交管理员数据（新增或修改）
    save() {
      const tempData = Object.assign({}, this.temp)
      const checkedKeys = this.$refs.tree.getCheckedKeys()
      tempData.permissions = checkedKeys
      const isEdit = this.dialogType === 'edit'
      if (isEdit) {
        update(tempData, tempData.id).then(res => {
          this.getList()
          this.dialog = false
          this.$notify({
            title: '修改管理员资料',
            message: res.message,
            type: 'success',
            duration: 2000
          })
        })
      } else {
        store(tempData).then(res => {
          this.getList()
          this.dialog = false
          this.$notify({
            title: '添加管理员',
            message: res.message,
            type: 'success',
            duration: 2000
          })
        })
      }
    },
    // 删除
    del(id) {
      if (id === 1) {
        this.$message({
          message: '超级管理员无法删除',
          type: 'error',
          duration: 5 * 1000
        })
      } else {
        this.$confirm('是否删除该角色？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          const res = await destroy(id)
          this.getList()
          this.$notify({
            title: '删除管理员',
            message: res.message,
            type: 'success',
            duration: 2000
          })
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
  .app-container {
    .filter {
      margin-bottom: 20px;

      .filter-input {
        margin-right: 10px;
      }
    }
  }
</style>

